'use strict';
const db = uniCloud.database();
const $ = db.command.aggregate
exports.main = async (event, context) => {
  //event为客户端上传的参数
  // console.log('event : ', event)
  let {
    flag,
    userID
  } = event
  let res
  if (flag == 1) {
    // collection
    res = db.collection("zhimuta-collection")
      .aggregate()
      .match({
        userID
      })
      .lookup({
        from: "zhumuta-cash-info",
        localField: "cashID",
        foreignField: "_id",
        as: "cashInfo"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$cashInfo', 0], "$$ROOT")])
      })
      .project({
        // cashInfo: 0,
        "avatar.url": 1
      })
      .end()
  }
  if (flag == 2) {
    // finishList
    res = db.collection("zhimuta-finish")
      .aggregate()
      .match({
        userID
      })
      .lookup({
        from: "zhumuta-cash-info",
        localField: "cashID",
        foreignField: "_id",
        as: "cashInfo"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$cashInfo', 0], "$$ROOT")])
      })
      .project({
        // cashInfo: 0,
        "avatar.url": 1
      })
      .end()
  }
  if (flag == 3) {
    // collection
    res = db.collection("zhimuta-collection")
      .aggregate()
      .match({
        userID
      })
      .lookup({
        from: "zhumuta-cash-info",
        localField: "cashID",
        foreignField: "_id",
        as: "cashInfo"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$cashInfo', 0], "$$ROOT")])
      })
      .end()
  }
  if (flag == 4) {
    // finishList
    res = db.collection("zhimuta-finish")
      .aggregate()
      .match({
        userID
      })
      .lookup({
        from: "zhumuta-cash-info",
        localField: "cashID",
        foreignField: "_id",
        as: "cashInfo"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$cashInfo', 0], "$$ROOT")])
      })
      .end()
  }
  //返回数据给客户端
  return res
};